package com.hxexp.weixin.mvc.common.service.impl;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.hxexp.weixin.common.config.DeployConfig;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.common.web.CookieUtil;
import com.hxexp.weixin.constant.CookieName;
import com.hxexp.weixin.mvc.common.service.SNSOauth2Service;
import com.qq.weixin.constant.AppDevConstant;
import com.qq.weixin.mp.api.oauth2.Oauth2API;
import com.qq.weixin.mp.api.oauth2.model.WebAccessTokenBean;
import com.qq.weixin.mp.api.oauth2.model.WebUserInfoBean;

/**
 * 网页授权服务实现类
 *
 * @author li.jiang
 *
 */
@Service
public final class SNSOauth2ServiceImpl implements SNSOauth2Service {
    private static final Logger LOGGER = LoggerFactory.getLogger(SNSOauth2ServiceImpl.class);
    // cookie有效期,单位：秒
    private static final int COOKIE_MAX_AGE = 86400 * 15;
    @Autowired
    private Oauth2API oauth2API;
    @Autowired
    private DeployConfig deployConfig;

    @Override
    public String setOpenid2Cookie(String code, HttpServletResponse response) throws ServiceException {
        if (!StringUtils.isEmpty(code)) {
            String appId = AppDevConstant.getAppId(deployConfig.getDeployEnvironment());
            String appSecret = AppDevConstant.getAppSecret(deployConfig.getDeployEnvironment());

            LOGGER.debug("*********** 换取网页授权token的code参数：{}", code);
            // 获取微信公众平台网页授权信息
            try {
                WebAccessTokenBean tokenBean = oauth2API.getAccessToken(code, appId, appSecret);
                // 将openid加密后保存到cookie
                //                String openid = AESHelper.encryptString(tokenBean.getOpenid(), AppDevConstant.OPENIDSECRET); 由于服务器运行环境的问题，暂时取消对openid加密
                CookieUtil.addCookie(response, CookieName.OPENID, tokenBean.getOpenid(), COOKIE_MAX_AGE);

                LOGGER.debug("************ 网页授权返回结果：{}", tokenBean);
                LOGGER.debug("************ 拉取微信用户信息参数：accesssToken={}, openid={}", tokenBean.getAccessToken(), tokenBean.getOpenid());
                WebUserInfoBean userInfo = oauth2API.getUserInfo(tokenBean.getAccessToken(), tokenBean.getOpenid());
                LOGGER.debug("************ 拉取微信用户信息返回结果：{}", userInfo);

                return tokenBean.getOpenid();
            } catch (Exception e) {
                LOGGER.error("获取微信公众平台网页授权发生异常", e);
                throw new ServiceException(e);
            }
        } else {
            return "";
        }
    }
}
